<template>
  <div style="padding: 20px;">
    <el-table
      v-loading="loading.directorLoading"
      element-loading-text="加载中"
      :data="directorClassList"
      :expand-row-keys="directorExpandRowKeys"
      :row-key="directorRowKey"
      border
      style="width: 100%"
      @expand-change="expandChangeHandler"
    >
      <el-table-column label="展示课表" type="expand">
        <template>
          <el-table v-loading="loading.timetableLoading" :data="timetableArr" element-loading-text="加载中" border style="width: 100%">
            <el-table-column label="周一" align="center">
              <template slot-scope="scope">
                <div v-if="scope.row.monday &&scope.row.monday.coursesId !== -1">
                  <el-tag type="primary" disable-transitions>
                    {{ scope.row.monday.coursesName }}
                  </el-tag>
                  <div style="text-align: center; color: #b598a1;">
                    {{ scope.row.monday.startTime }} - {{ scope.row.monday.endTime }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="周二" align="center">
              <template slot-scope="scope">
                <div v-if="scope.row.tuesday && scope.row.tuesday.coursesId !== -1">
                  <el-tag type="primary" disable-transitions>
                    {{ scope.row.tuesday.coursesName }}
                  </el-tag>
                  <div style="text-align: center; color: #b598a1;">
                    {{ scope.row.tuesday.startTime }} - {{ scope.row.tuesday.endTime }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="周三" align="center">
              <template slot-scope="scope">
                <div v-if="scope.row.wednesday && scope.row.wednesday.coursesId !== -1">
                  <el-tag type="primary" disable-transitions>
                    {{ scope.row.wednesday.coursesName }}
                  </el-tag>
                  <div style="text-align: center; color: #b598a1;">
                    {{ scope.row.wednesday.startTime }} - {{ scope.row.wednesday.endTime }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="周四" align="center">
              <template slot-scope="scope">
                <div v-if="scope.row.thursday && scope.row.thursday.coursesId !== -1">
                  <el-tag type="primary" disable-transitions>
                    {{ scope.row.thursday.coursesName }}
                  </el-tag>
                  <div style="text-align: center; color: #b598a1;">
                    {{ scope.row.thursday.startTime }} - {{ scope.row.thursday.endTime }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="周五" align="center">
              <template slot-scope="scope">
                <div v-if="scope.row.friday && scope.row.friday.coursesId !== -1">
                  <el-tag type="primary" disable-transitions>
                    {{ scope.row.friday.coursesName }}
                  </el-tag>
                  <div style="text-align: center; color: #b598a1;">
                    {{ scope.row.friday.startTime }} - {{ scope.row.friday.endTime }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="周六" align="center">
              <template slot-scope="scope">
                <div v-if="scope.row.saturday && scope.row.saturday.coursesId !== -1">
                  <el-tag type="primary" disable-transitions>
                    {{ scope.row.saturday.coursesName }}
                  </el-tag>
                  <div style="text-align: center; color: #b598a1;">
                    {{ scope.row.saturday.startTime }} - {{ scope.row.saturday.endTime }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="周日" align="center">
              <template slot-scope="scope">
                <div v-if="scope.row.sunday && scope.row.sunday.coursesId !== -1">
                  <el-tag type="primary" disable-transitions>
                    {{ scope.row.sunday.coursesName }}
                  </el-tag>
                  <div style="text-align: center; color: #b598a1;">
                    {{ scope.row.sunday.startTime }} - {{ scope.row.sunday.endTime }}
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column prop="classCode" label="班级代码" />
      <el-table-column prop="name" label="班级名称" />
      <el-table-column prop="type" label="班级性质" />
      <el-table-column prop="desc" label="班级介绍" />
      <el-table-column fixed="right" align="center" label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="editTimetable(scope.row)">编辑课表</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 操作框 -->
    <el-dialog title="编辑课表" :visible.sync="operaShow" :close-on-click-modal="false">
      <el-row>
        <el-col v-for="(item, index) of timetableForms" :key="index" :span="12">
          <!-- 编辑课程 -->
          <el-form :model="item">
            <el-form-item label="课程日" label-position="top" label-width="80px">
              <el-select v-model="item.day" placeholder="请选择">
                <el-option
                  v-for="ditem in dateSelections"
                  :key="ditem.value"
                  :label="ditem.label"
                  :value="ditem.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="课程" label-position="left" label-width="80px">
              <el-select v-model="item.coursesSelect" value-key="id" placeholder="请选择" @change="coursesChangeHandler(item)">
                <el-option
                  v-for="citem in classCoursesList"
                  :key="citem.coursesId"
                  :label="citem.name"
                  :value="{ id: citem.coursesId, name: citem.name }"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="课程时间" label-position="left" label-width="80px">
              <el-time-picker
                v-model="item.timer"
                is-range
                arrow-control
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择时间范围"
                format="HH:mm"
                @change="timePickerChangeHandler(item)"
              />
            </el-form-item>
          </el-form>
          <div style="text-align: right;">
            <el-button v-if="index !== 0" icon="el-icon-minus" circle @click="removeTimetableForm(index)" />
            <el-button icon="el-icon-plus" circle @click="addTimetableForm()" />
          </div>
        </el-col>
        <el-col :span="24" style="text-align: right; margin-top: 30px;">
          <el-button @click="operaShow = false">取 消</el-button>
          <el-button type="primary" @click="operaConfirmHandler()">确 定</el-button>
        </el-col>
      </el-row>

    </el-dialog>
  </div>
</template>

<script>
import { info, directorClass, arrangeTimetable } from '@/api/class'
import { classCourses } from '@/api/class_courses'
import { Message } from 'element-ui'

const DAY_MAP = {
  '0': 'monday',
  '1': 'tuesday',
  '2': 'wednesday',
  '3': 'thursday',
  '4': 'friday',
  '5': 'saturday',
  '6': 'sunday'
}
export default {
  data() {
    return {
      dateSelections: [
        {
          label: '星期一',
          value: 'monday'
        },
        {
          label: '星期二',
          value: 'tuesday'
        },
        {
          label: '星期三',
          value: 'wednesday'
        },
        {
          label: '星期四',
          value: 'thursday'
        },
        {
          label: '星期五',
          value: 'friday'
        },
        {
          label: '星期六',
          value: 'saturday'
        },
        {
          label: '星期日',
          value: 'sunday'
        }
      ],
      operaShow: false,
      loading: {
        directorLoading: true,
        timetableLoading: true
      },
      // 编辑课表
      form: {
        classId: 0,
        className: '',
        monday: [],
        tuesday: [],
        wednesday: [],
        thursday: [],
        friday: [],
        saturday: [],
        sunday: []
        // coursesId: 0,
        // coursesName: '',
        // startTime: '',
        // endTime: ''
      },
      // 负责扩展的行 keys
      directorExpandRowKeys: [],
      // 课程表 - 动态变化
      timetable: {},
      timetableArr: [],
      // 课程表 - 动态表单
      timetableForms: [],
      // 班级的课程 - 动态
      classCoursesList: [],
      // 负责的班级
      directorClassList: [],
      // 临时课表数据
      tempTimetable: {
        row: {},
        expandedRows: []
      }
    }
  },
  watch: {
    operaShow(n) {
      // 关闭时初始化数据
      if (!n) {
        this.timetableForms = []
        this.classCoursesList = []
      }
    }
  },
  mounted() {
    this.loading.directorLoading = true
    directorClass().then(res => {
      this.directorClassList = res.data
    }).finally(() => {
      this.loading.directorLoading = false
    })
  },
  methods: {
    directorRowKey(row) {
      return row.id
    },
    async expandChangeHandler(row, expandedRows) {
      // 确保只展开一行
      if (expandedRows.length > 0) {
        this.tempTimetable.row = row
        this.tempTimetable.expandedRows = expandedRows
        this.directorExpandRowKeys = []
        const res = await info(row.id)
        this.loading.timetableLoading = true
        if (res.data.timetable) {
          this.timetable = JSON.parse(res.data.timetable)
          // 根据数组长度，进行排序
          const monthTimetable = []
          for (const key in this.timetable) {
            const list = this.timetable[key]
            if (monthTimetable.length === 0) {
              monthTimetable.push(list)
            } else {
              for (let i = monthTimetable.length - 1; i >= 0; i--) {
                const temp = monthTimetable[i]
                if (list.length > temp.length) {
                  monthTimetable[i] = list
                  monthTimetable[i + 1] = temp
                } else {
                  monthTimetable.push(list)
                }
              }
            }
          }
          // 将横型数组改成竖形数组
          const latArr = []
          const maxLenArr = monthTimetable[0]
          for (let i = 0; i < maxLenArr.length; i++) {
            const tempObj = {}
            let j = 0
            for (const key in this.timetable) {
              const list = this.timetable[key]
              let tempVal = list[i]
              if (!tempVal) {
                // 值不存在
                tempVal = {
                  coursesId: -1,
                  endTime: '',
                  startTime: '',
                  coursesName: ''
                }
              }
              tempObj[DAY_MAP[j + '']] = tempVal
              j++
            }
            latArr.push(tempObj)
          }
          this.timetableArr = latArr
        } else {
          this.timetableArr = []
        }
        this.loading.timetableLoading = false
        this.directorExpandRowKeys.push(row.id)
        // info(row.id).then(res => {
        //   console.log('res.data = ', res.data)
        //   if (res.data.timetable) {
        //     this.timetable = JSON.parse(res.data.timetable)
        //     // 根据数组长度，进行排序
        //     const monthTimetable = []
        //     for (const key in this.timetable) {
        //       const list = this.timetable[key]
        //       if (monthTimetable.length === 0) {
        //         monthTimetable.push(list)
        //       } else {
        //         for (let i = monthTimetable.length - 1; i >= 0; i--) {
        //           const temp = monthTimetable[i]
        //           if (list.length > temp.length) {
        //             monthTimetable[i] = list
        //             monthTimetable[i + 1] = temp
        //           } else {
        //             monthTimetable.push(list)
        //           }
        //         }
        //       }
        //     }
        //     // 将横型数组改成竖形数组
        //     const latArr = []
        //     const maxLenArr = monthTimetable[0]
        //     for (let i = 0; i < maxLenArr.length; i++) {
        //       const tempObj = {}
        //       let j = 0
        //       for (const key in this.timetable) {
        //         const list = this.timetable[key]
        //         let tempVal = list[i]
        //         if (!tempVal) {
        //           // 值不存在
        //           tempVal = {
        //             coursesId: -1,
        //             endTime: '',
        //             startTime: '',
        //             coursesName: ''
        //           }
        //         }
        //         tempObj[DAY_MAP[j + '']] = tempVal
        //         j++
        //       }
        //       latArr.push(tempObj)
        //     }
        //     this.timetableArr = latArr
        //     console.log(this.timetableArr)
        //     // // 将横型数组改成竖形数组 error plan
        //     // const lastArr = []
        //     // // 获取最长的数组
        //     // const maxLenArr = monthTimetable[0]
        //     // for (let i = 0; i < maxLenArr.length; i++) {
        //     //   const tempObj = {}
        //     //   const maxVal = maxLenArr[i]
        //     //   tempObj.monday = maxVal
        //     //   for (let j = 1; j < monthTimetable.length; j++) {
        //     //     const sunVal = monthTimetable[j][i]
        //     //     tempObj[DAY_MAP[j + '']] = sunVal
        //     //   }
        //     //   lastArr.push(tempObj)
        //     // }
        //     // this.timetableArr = lastArr
        //   } else {
        //     this.timetableArr = []
        //   }
        // })
      }
    },
    editTimetable(row) {
      this.form.classId = row.id
      this.form.className = row.name
      this.timetableForms.push({
        classId: this.form.classId,
        coursesId: null,
        coursesName: '',
        startTime: '08:30',
        endTime: '09:30',
        timer: [new Date(2016, 9, 10, 8, 30), new Date(2016, 9, 10, 9, 30)]
      })
      classCourses(row.id).then(res => {
        this.classCoursesList = res.data
      })
      this.operaShow = true
    },
    addTimetableForm() {
      this.timetableForms.push({
        classId: this.form.classId,
        coursesId: null,
        coursesName: '',
        startTime: '08:30',
        endTime: '09:30',
        timer: [new Date(2016, 9, 10, 8, 30), new Date(2016, 9, 10, 9, 30)]
      })
    },
    removeTimetableForm(index) {
      this.timetableForms.splice(index, 1)
    },
    operaConfirmHandler() {
      // 构建日期数据
      this.form.monday = this.timetableForms.filter(form => form.day === 'monday')
      this.form.tuesday = this.timetableForms.filter(form => form.day === 'tuesday')
      this.form.wednesday = this.timetableForms.filter(form => form.day === 'wednesday')
      this.form.thursday = this.timetableForms.filter(form => form.day === 'thursday')
      this.form.friday = this.timetableForms.filter(form => form.day === 'friday')
      this.form.saturday = this.timetableForms.filter(form => form.day === 'saturday')
      this.form.sunday = this.timetableForms.filter(form => form.day === 'sunday')
      arrangeTimetable(this.form).then(res => {
        Message({
          message: '编辑课程表成功',
          type: 'success',
          duration: 5 * 1000
        })
        // 重新获取课程
        this.expandChangeHandler(this.tempTimetable.row, this.tempTimetable.expandedRows)
        this.operaShow = false
      })
    },
    timePickerChangeHandler(item) {
      const startTime = item.timer[0].format('HH:mm')
      const endTime = item.timer[1].format('HH:mm')
      item.startTime = startTime
      item.endTime = endTime
    },
    coursesChangeHandler(item) {
      item.coursesId = item.coursesSelect.id
      item.coursesName = item.coursesSelect.name
    }
  }
}
</script>

